<Route>
在整个react-router中,算是最重要的组件了。匹配不同的路由,渲染UI。
Route组件渲染方法:
- component
- render
- children
可以通过上述这3种方式来渲染内容。在一个<Route>中不可以同时出现,针对不同的应用场景采取不同的方式:
component
传递一个组件,常规组件或者class组件:
import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter as Router,Route} from 'react-router-dom';
class Home extends React.Component{
render(){
return(
<h1>This is Home</h1>
)
}
}
ReactDOM.render(
<Router>
<div>
<Route path="/" component={Home} />
</div>
</Router>,
document.querySelector("#root")
);
路由的match、history、location属性将传递给Home组件的props。
这种方式实际上就是调用了React.createElement方法,传递Home。
render:func
这种方式一般传递一个函数,函数体内返回要渲染的React元素。
<Route path="/" render={(props)=>(<h1>This is Home</h1>)} />
函数传递一个props属性,该属性包涵了匹配路由的match、history、location。
children:func
这个属性类似于render,函数同样传递一个包含路由match、history、location属性的对象。
<Route path="/" children={(props)=>(<h1>{JSON.stringify(props.match)}</h1>)} />
不同的是,无论路由是否匹配,都会渲染。只不过未匹配的路由,match属性值为null。因此可以利用这一点,动态判断当前路由是否匹配。比如导航菜单的底色变化,就可以以此来实现。
import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter as Router,Route,Link} from 'react-router-dom';
class ActiveLink extends React.Component{
render(){
return(
<Route exact path={this.props.to} children={(props)=>{
return <span className={props.match?'active':''}><Link to={this.props.to} children={this.props.children} /></span>
}} />
)
}
}
ReactDOM.render(
<Router>
<div>
<ActiveLink to="/" children="home" />
<ActiveLink to="/about" children="about" />
<Route exact path="/" render={(props)=>(<h1>Home</h1>)} />
<Route exact path="/about" render={(props)=>(<h1>About</h1>)} />
</div>
</Router>,
document.querySelector("#root")
);
在这个例子中,匹配到的路由a标签会多一个active的className。因为需要动态判断,所以<Link>需要包在<Route>之中。
children通常用于动画中,后续会专门介绍React的一个动画组件——"react-transition-group"。
Route组件的常规属性:
path:string
匹配路由,当成功匹配,则会渲染component的组件或者render函数。
exact:boolean
是否精确匹配,默认false。一般都要添加该属性。
| path | location.pathname | exact | match? |
|---|---|---|---|
| /one | /one/two | true | no |
| /one | /one/two | false | yes |
strict:boolean
是否严格匹配,默认false。一般不添加该属性。
| path | location.pathname | match? |
|---|---|---|
| /one/ | /one | no |
| /one/ | /one/ | yes |
| /one/ | /one/two | yes |
一般与exact一起使用。
location:object
重写匹配该路由的location,但一般不这么做,用法请参考 《Link & NavLink 组件》一章,用法一致。